let upload = require('../../common/upload')
Page({
    behaviors: [upload],
    data: {
        supplierInfo: '', //上页传递的供应商信息
        goodInfo: null, //上页传递的商品信息
        message: '',
        voucher: [],
        voucherFormData: { from: 'comment' },
        score: 0,
        buttonLoading: false
    },
    onLoad: function(options) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', ({ data }) => {
            this.setData({
                supplierInfo: data.supplierInfo,
                goodInfo: data.goodInfo
            })
        })
    },
    onChange(event) {
        this.setData({ score: event.detail })
    },
    submit() {
        if (this.data.message === '') return wx.showToast({
            title: '请输入您的评价',
            icon: 'none'
        })

        if (this.data.score === 0) {
            return wx.showToast({
                title: '请选择评分',
                icon: 'none'
            })
        }
        for (let i = 0; i < this.data.voucher.length; i++) {
            if (this.data.voucher[i].status !== 'done') {
                return wx.showToast({
                    title: '有图片正在上传或上传失败',
                    icon: 'none'
                })
            }
        }
        this.setData({ buttonLoading: true })
        const { goodInfo, score, message, voucher } = this.data
        let reqData = {
            order_id: goodInfo.order_id,
            order_product_id: goodInfo.order_product_id,
            score,
            content: message
        }
        if (voucher.length > 0) {
            let photos = voucher.map(item => {
                return item.uploadPath
            })
            reqData.photos = photos.join(',')
        }
        this.request({
            url: '/api/order/comment',
            method: 'POST',
            data: reqData
        }, () => {
            wx.showToast({
                title: '评价成功',
                icon: 'success',
                mask: true
            })
            const eventChannel = this.getOpenerEventChannel()
            eventChannel.emit('markEvaluate')
            this.delay(() => {
                wx.navigateBack()
            })
        }, () => {
            this.setData({
                buttonLoading: false
            })
        })
    }
})